You write custom CUDA kernels to replace the pytorch operators in the given GeGLU architecture to get speedups.

You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.

Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline

BYOL (Bootstrap Your Own Latent) loss computation (2-2·cosine similarity)

Per-sample parallelization (one thread per batch element)

In-kernel L2 normalization with manual norm calculation

Cosine similarity computation with explicit dot product

Symmetric loss computation between two augmented views

Fixed block size (256 threads) with dynamic grid sizing

Contiguous memory access with pointer arithmetic

Two kernel launches for symmetric loss terms

Mean reduction across batch dimension





Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, p1: torch.Tensor, z2: torch.Tensor, p2: torch.Tensor, z1: torch.Tensor) -> torch.Tensor:
        p1_norm = torch.nn.functional.normalize(p1, dim=-1)
        z2_norm = torch.nn.functional.normalize(z2, dim=-1)
        loss1 = 2 - 2 * (p1_norm * z2_norm).sum(dim=-1)

        p2_norm = torch.nn.functional.normalize(p2, dim=-1)
        z1_norm = torch.nn.functional.normalize(z1, dim=-1)
        loss2 = 2 - 2 * (p2_norm * z1_norm).sum(dim=-1)

        loss = (loss1 + loss2).mean()
        return loss


batch_size = 16
dim = 128


def get_inputs():
    p1 = torch.randn(batch_size, dim)
    z2 = torch.randn(batch_size, dim)
    p2 = torch.randn(batch_size, dim)
    z1 = torch.randn(batch_size, dim)
    return [p1, z2, p2, z1]


def get_init_inputs():
    return []